package com.app.controller;

import com.app.model.AdminUserModel;
import com.app.model.DepartmentModel;
import com.app.model.PersonModel;
import com.app.model.TaskModel;
import com.app.service.AdminUserService;
import com.app.service.DepartmentService;
import com.app.service.PersonService;
import com.app.service.TaskService;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.vo.TaskVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@RestController
@Controller
@RequestMapping("/api/task")
public class TaskController {
    @Autowired
    private TaskService taskService;
    @Autowired
    private PersonService personService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private AdminUserService adminUserService;

    /**
     * 任务进度管理
     */
    //列表查询
    @GetMapping("/selectTaskList")
    public Result<Object> selectTaskList(String name, Integer page, Integer limit, HttpServletRequest request,Integer sortType) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }

        TaskVo vo = new TaskVo();
        if (user.getId() == 1) {
            user.setDepartmentId(null);
        }
        IPage<TaskModel> taskModelPage = taskService.selectTaskList(name, page, limit, user.getDepartmentId(),sortType);
        List<TaskModel> records = taskModelPage.getRecords();
        for (int i = 0; i < records.size(); i++) {
            List<String> idsList = Arrays.asList(records.get(i).getDepartmentId().split(","));
            records.get(i).setDepartment(idsList);
            List<DepartmentModel> depByDepId = departmentService.getDepList(idsList);
            StringBuilder sb = new StringBuilder();
            for (DepartmentModel departmentModel : depByDepId) {
                sb.append(departmentModel.getName()).append(" | ");
            }
            sb.deleteCharAt(sb.length() - 2);
            records.get(i).setDepartmentText(sb.toString());
        }
        int total = (int) taskModelPage.getTotal();
        vo.setList(records);
        vo.setCount(total);
        return Result.success(vo);
    }

    //任务进度提示
    @GetMapping("/warnTask")
    public Result<Object> warnTask(HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.success(0);
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        List<TaskModel> taskModels = taskService.selectAll(user.getDepartmentId());
        List<TaskModel> taskModelList = new ArrayList<>();
        for (TaskModel model : taskModels) {
            Timestamp taskTime = model.getTaskTime();
            Integer warnTime = model.getWarnTime();
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime with = now.with(LocalTime.MIN);
            LocalDateTime localDateTime = with.plusDays(warnTime);
            if (localDateTime.compareTo(taskTime.toLocalDateTime()) == 0) {
                TaskModel taskModel = new TaskModel();
                taskModel.setContent(model.getName() + "任务还有" + model.getWarnTime() + "天到期");
                taskModel.setId(model.getId());
                taskModelList.add(taskModel);
            }
        }
        return Result.success(taskModelList);
    }

    //新增和编辑任务进度
    @PostMapping("/insertAndUpdateTask")
    public Result<Object> insertAndUpdateTask(@RequestBody TaskModel taskModel, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        if (taskModel.getId() > 0) {
            taskModel.setUpdateTime(CommonHelp.getNowTimestamp());
            taskService.update(taskModel);
        } else {
            taskModel.setCreateTime(CommonHelp.getNowTimestamp());
            taskService.insert(taskModel);
        }
        return Result.success("操作成功");
    }

    //删除任务进度
    @GetMapping("/delectTask")
    public Result<Object> deleteTask(Integer id, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        taskService.delete(id);
        return Result.success("操作成功");
    }

}
